<template>
  <div class="reader-container">
    <!-- PDF显示区域 -->
    <div class="pdf-container">
      <div class="pdf-toolbar">
        <a-upload
          accept=".pdf"
          :show-upload-list="false"
          :before-upload="handleFileSelect"
        >
          <a-button type="primary">
            <a-icon type="upload" /> 选择PDF文件
          </a-button>
        </a-upload>
        <a-button-group v-if="pdfDoc">
          <a-button @click="zoomOut">
            <a-icon type="zoom-out" />
          </a-button>
          <a-button @click="zoomIn">
            <a-icon type="zoom-in" />
          </a-button>
        </a-button-group>
        <div v-if="pdfDoc" class="page-nav">
          <a-input-number
            v-model="currentPage"
            :min="1"
            :max="totalPages"
            @change="handlePageChange"
          />
          <span>/ {{ totalPages }}</span>
        </div>
      </div>
      <div ref="pdfViewer" class="pdf-viewer">
        <div ref="pdfContainer" class="pdf-container-inner"></div>
        <div ref="textLayer" class="text-layer"></div>
      </div>
    </div>

    <!-- 控制台输出区域 -->
    <div class="console-container">
      <div class="console-header">
        <span>控制台输出</span>
        <a-button type="link" @click="clearConsole">清空</a-button>
      </div>
      <div class="console-content" ref="consoleContent">
        <div
          v-for="(log, index) in consoleLogs"
          :key="index"
          class="console-item"
        >
          <span class="timestamp">{{ log.time }}</span>
          <pre class="message">{{ log.message }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as pdfjsLib from "pdfjs-dist";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

// 配置 PDF.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;

export default {
  name: "ReaderPage",
  data() {
    return {
      pdfDoc: null,
      currentPage: 1,
      totalPages: 0,
      scale: 1,
      consoleLogs: [],
      currentTextContent: null,
    };
  },
  methods: {
    // 处理文件选择
    async handleFileSelect(file) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          await this.loadPdf(e.target.result);
          this.logToConsole(`成功加载PDF文件: ${file.name}`);
        } catch (error) {
          this.logToConsole(`加载PDF失败: ${error.message}`, "error");
        }
      };
      reader.readAsArrayBuffer(file);
      return false;
    },

    // 加载PDF文件
    async loadPdf(data) {
      try {
        // PDFDocumentLoadingTask
        const loadingTask = pdfjsLib.getDocument(new Uint8Array(data));

        // PDFDocumentProxy ：{ numPages ， loadingTask， ... }
        this.pdfDoc = await loadingTask.promise;
        this.totalPages = this.pdfDoc.numPages;
        await this.renderPage(1);
      } catch (error) {
        console.error("PDF加载失败:", error);
        throw error;
      }
    },

    // 渲染PDF页面
    async renderPage(num) {
      if (!this.pdfDoc) return;

      try {
        const page = await this.pdfDoc.getPage(num);
        const viewport = page.getViewport({ scale: this.scale });
        const outputScale = window.devicePixelRatio || 1;

        // 准备 canvas
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.width = viewport.width * outputScale;
        canvas.height = viewport.height * outputScale;
        canvas.style.width = `${viewport.width}px`;
        canvas.style.height = `${viewport.height}px`;

        // 渲染 PDF 页面到 canvas
        const renderContext = {
          canvasContext: context,
          viewport: viewport,
          transform:
            outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null,
        };

        const renderTask = page.render(renderContext);

        // 获取文本内容
        const textContent = await page.getTextContent();
        this.currentTextContent = textContent;

        // 清空容器
        const container = this.$refs.pdfContainer;
        const textLayer = this.$refs.textLayer;
        container.innerHTML = "";
        textLayer.innerHTML = "";

        // 设置容器尺寸和位置
        container.style.position = "relative";
        container.style.width = `${viewport.width}px`;
        container.style.height = `${viewport.height}px`;

        textLayer.style.position = "absolute";
        textLayer.style.left = "0";
        textLayer.style.top = "0";
        textLayer.style.width = `${viewport.width}px`;
        textLayer.style.height = `${viewport.height}px`;
        textLayer.style.transform = "";

        // 添加 canvas
        container.appendChild(canvas);

        // 文字层
        const textLayerDiv = document.createElement("div");
        textLayerDiv.className = "textLayer";
        textLayerDiv.style.position = "absolute";
        textLayerDiv.style.left = "0";
        textLayerDiv.style.top = "0";
        textLayerDiv.style.width = `${viewport.width}px`;
        textLayerDiv.style.height = `${viewport.height}px`;
        // 关键：同步缩放
        if (outputScale !== 1) {
          textLayerDiv.style.transform = `scale(${outputScale})`;
          textLayerDiv.style.transformOrigin = "0 0";
        }
        container.appendChild(textLayerDiv);

        // 渲染文字层
        const textLayerParams = {
          textContent: textContent,
          container: textLayerDiv,
          viewport: viewport,
          textDivs: [],
          enhanceTextSelection: true,
        };
        await pdfjsLib.renderTextLayer(textLayerParams).promise;

        // 添加文本选择事件监听
        textLayer.addEventListener("mouseup", this.handleTextSelection);

        this.logToConsole(`渲染第 ${num} 页`);
      } catch (error) {
        this.logToConsole(`渲染页面失败: ${error.message}`, "error");
      }
    },

    // 处理文本选择
    handleTextSelection() {
      const selection = window.getSelection();
      const selectedText = selection.toString().trim();

      if (selectedText && this.currentTextContent) {
        // 获取选择范围
        const range = selection.getRangeAt(0);
        const textLayer = this.$refs.textLayer;

        // 确保选择在文本层内
        if (textLayer.contains(range.commonAncestorContainer)) {
          this.logToConsole(`选中的文本: ${selectedText}`);

          // 获取选择位置
          const rect = range.getBoundingClientRect();
          const layerRect = textLayer.getBoundingClientRect();
          const relativeTop = rect.top - layerRect.top;
          const relativeLeft = rect.left - layerRect.left;

          this.logToConsole(
            `选中位置: 距顶部 ${Math.round(relativeTop)}px, 距左侧 ${Math.round(
              relativeLeft
            )}px`
          );
        }
      }
    },

    // 页面切换
    handlePageChange(pageNum) {
      this.currentPage = pageNum;
      this.renderPage(pageNum);
    },

    // 缩放控制
    zoomIn() {
      this.scale = Math.min(this.scale * 1.2, 3.0);
      this.renderPage(this.currentPage);
    },
    zoomOut() {
      this.scale = Math.max(this.scale / 1.2, 0.5);
      this.renderPage(this.currentPage);
    },

    // 控制台相关方法
    logToConsole(message, type = "info") {
      const time = new Date().toLocaleTimeString();
      this.consoleLogs.push({ time, message, type });
      this.$nextTick(() => {
        const consoleContent = this.$refs.consoleContent;
        consoleContent.scrollTop = consoleContent.scrollHeight;
      });
    },

    clearConsole() {
      this.consoleLogs = [];
    },
  },
  beforeDestroy() {
    // 移除事件监听
    const textLayer = this.$refs.textLayer;
    if (textLayer) {
      textLayer.removeEventListener("mouseup", this.handleTextSelection);
    }
  },
};
</script>

<style scoped>
.reader-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.pdf-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.pdf-toolbar {
  padding: 8px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-nav {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pdf-viewer {
  flex: 1;
  overflow: auto;
  padding: 16px;
  background-color: #f5f5f5;
  position: relative;
}

.pdf-container-inner {
  position: relative;
  margin: 0 auto;
  background: #fff;
}

canvas {
  display: block;
  position: absolute;
  left: 0;
  top: 0;
}

.textLayer {
  position: absolute;
  left: 0;
  top: 0;
  pointer-events: auto;
  opacity: 1;
  user-select: text;
}

.console-container {
  height: 200px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.console-header {
  padding: 8px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.console-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  background: #fff;
  font-family: monospace;
}

.console-item {
  margin-bottom: 4px;
  display: flex;
  gap: 8px;
}

.timestamp {
  color: #888;
  white-space: nowrap;
}

.message {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
